﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using DG.Tweening;

public class UIMainMeun : MonoBehaviour {
    public PopArcButton buildTower;
    public LevelUserView levelUserView;
    public StartGameView startGameView;
    public TowerInfo_View towerInfo_View;
    public EndGameView endGameView;
    public Button next;
    TowerBase currSelect;
    public static UIMainMeun Instance;
    private void Awake() {
        Instance=this;
        startGameView.Init();

    }
    void Start () {
        Cameracontroller.selectTower += SelectTower;
        GameManager.Instance.onEndGame += EndGame;
    }

    private void EndGame(float obj)
    {
        endGameView.EndGame(obj);
    }

    void OnDestroy(){
          Cameracontroller.selectTower -= SelectTower;
        GameManager.Instance.onEndGame -= EndGame;
    }

    private void SelectTower(TowerBase obj)
    {
        if (!obj.HasTower)
        {
            currSelect = obj;
            buildTower.gameObject.SetActive(false);
            RectTransform rectTransform = buildTower.GetComponent<RectTransform>();
            rectTransform.anchoredPosition = GetScreenPosByObj(obj.transform);
            buildTower.gameObject.SetActive(true);
        }
        else{
            towerInfo_View.UpdateTowerInfo(obj);
            towerInfo_View.Show();
        }


    }

    public  void ShowNextButton(){
        next.GetComponent<DOTweenAnimation>().DOPlayForward();
    }
    private Vector2 GetScreenPosByObj(Transform tr)
    {
        Vector2 pos= Camera.main.WorldToViewportPoint(tr.position);
  
        Vector2 sizeDelta = transform.GetComponent<RectTransform>().sizeDelta;
        Vector2 position = new Vector2();
        position.x = pos.x * sizeDelta.x ;
        position.y = pos.y * sizeDelta.y;
        return position;

    }

    // Update is called once per frame
    void Update () {
        if (buildTower.gameObject.activeSelf)
        {
            RectTransform rectTransform = buildTower.GetComponent<RectTransform>();
            rectTransform.anchoredPosition = GetScreenPosByObj(currSelect.transform);
            if ((currSelect.transform.position-Camera.main.transform.position).magnitude>50)
            {
                buildTower.Close();
            }
        }
            
    }
    public void CreateTower(int index)
    {
        TowerType towerType = (TowerType)index;
        TowerBase tb= Cameracontroller.currSelectObj.GetComponent<TowerBase>();
        tb.CreatTower(towerType);
    }
}
